<?php
/*
 * Created on Nov 10, 2010
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 
class Password
{

	function Password()
	{
	}
	
	// This funstion validates a plain text password with an
	// encrpyted password
  	public function validate($plain, $encrypted) 
  	{
     	if (!empty($plain) && !empty($encrypted)) {
		
			// split apart the hash / salt
      		$stack = explode(':', $encrypted);

	      	if (sizeof($stack) != 2) 
	      		return false;
	
	      	if (md5($stack[1] . $plain) == $stack[0]) {
	        	return true;
	      	}
    	}

    	return false;
  	}


	// This function makes a new password from a plaintext password. 
  	public function encrypt($plain) 
  	{
   		$password = '';

    	for ($i=0; $i<10; $i++) {
      		$password .= $this->rand();
    	}

    	$salt = substr(md5($password), 0, 2);

    	$password = md5($salt . $plain) . ':' . $salt;

    	return $password;
  	}
  	
  	public function rand($min = null, $max = null)
  	{
    	static $seeded;

    	if (!$seeded) {
      		mt_srand((double)microtime()*1000000);
      		$seeded = true;
    	}

    	if (isset($min) && isset($max)) {
	      	if ($min >= $max) {
	        	return $min;
	      	} else {
	        	return mt_rand($min, $max);
	      	}
    	} else {
      		return mt_rand();
    	}
  	}
  	
	function getRandomValue($length, $type = 'mixed') 
	{
    	if ( ($type != 'mixed') && ($type != 'chars') && ($type != 'digits')) return false;

    	$rand_value = '';
    	while (strlen($rand_value) < $length) {
      		if ($type == 'digits') {
        		$char = rand(0, 9);
      		} else {
        		$char = chr(rand(0, 255));
      		}
      		
      		if ($type == 'mixed') {
        		if (eregi('^[a-z0-9]$', $char)) 
        			$rand_value .= $char;
      		} elseif ($type == 'chars') {
        		if (eregi('^[a-z]$', $char)) 
        			$rand_value .= $char;
  			} elseif ($type == 'digits') {
    			if (ereg('^[0-9]$', $char)) 
    				$rand_value .= $char;
  			}
    	}

    	return $rand_value;
  	}
  	
}
?>
